<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Socket.IO chat</title>
    <link rel="stylesheet" href="/public/css/chat.css"/>

</head>
<body>
</body>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
    socket = io.connect("http://localhost:3000/chat");
    var UserId = 0;
    var SessionId = "";
    var Groups = [], Friends = [];
    var messagesData = {};

    function hideChatView($) {
        $("#chatView").hide();
    }

    function createChatView($) {
        var i, len;
        var messagesViewList = ["messages"];
        messagesData.messages = [];

        var messages_id;
        var chatView =
                '<div id="chatView">'
                + ' <ul id="messages"></ul>';
        for (i = 0, len = Groups.length; i < len; i++) {
            messages_id = "messages_groups_" + Groups[i];
            messagesData[messages_id] = [];
            messagesViewList.push(messages_id);
            chatView += ' <ul id="messages_groups_' + Groups[i] + '" style="display:none"></ul>';
        }
        for (i = 0, len = Friends.length; i < len; i++) {
            messages_id = "messages_friends_" + Friends[i];
            messagesData[messages_id] = [];
            messagesViewList.push(messages_id);
            chatView += ' <ul id="messages_friends_' + Friends[i] + '" style="display:none"></ul>'
        }
        chatView +=
                ' <form action="" id="chatForm">'
                + '     <select name="" id="chatType">'
                + '         <option class="chatOptions" value="worldChat">世界聊天</option>'
                + '         <option class="chatOptions" value="groupChat">群组聊天</option>'
                + '         <option class="chatOptions" value="userChat">好友聊天</option>'
                + '     </select>';

        chatView += '     <select name="" id="typeGroupChat" style="display:none">';
        for (i = 0, len = Groups.length; i < len; i++) {
            chatView += '         <option class="groupChatOptions" value="' + Groups[i] + '">' + Groups[i] + '</option>'
        }
        chatView += '     </select>';

        chatView += '     <select name="" id="typeFriendsChat" style="display:none">';
        for (i = 0, len = Friends.length; i < len; i++) {
            chatView += '         <option class="friendsChatOptions" value="' + Friends[i] + '">' + Friends[i] + '</option>'
        }
        chatView += '     </select>';

        chatView +=
                '     <input id="m" class="world" autocomplete="off" />'
                + '     <button>Send</button>'
                + ' </form>'
                + '</div>';
        $(chatView).appendTo('body');

        function showChatView(id) {
            for (var i = 0, len = messagesViewList.length; i < len; i++) {
                var block = $("#" + messagesViewList[i]);
                if (messagesViewList[i] != id) {
                    block.hide();
                    console.log("hide %s <=> %s", messagesViewList[i], id);
                } else {
                    block.show();
                    console.log("show %s <=> %s", messagesViewList[i], id);
                }
            }
        }

        $('#chatForm').submit(function () {
            var messagesBox = $('#m');
            var chatType = $("#chatType").children('option:selected').val();
            var chatViewId = "messages";
            switch (chatType) {
                case "worldChat":
                    socket.emit('world messages', messagesBox.val());
                    break;
                case "groupChat":
                    var groupId = $("#typeGroupChat").children('option:selected').val();
                    chatViewId += "_groups_" + groupId;
                    socket.emit('group messages', groupId, messagesBox.val());
                    break;
                case "userChat":
                    var friendId = $("#typeFriendsChat").children('option:selected').val();
                    chatViewId += "_friends_" + friendId;
                    socket.emit('p2p messages', friendId, messagesBox.val());
                    break;
                default:
                    break;
            }
            showChatView(chatViewId);
            $("#" + chatViewId).append($('<li>').text("Mine: " + messagesBox.val()));
            messagesBox.val('');
            return false;
        });

        $("#chatType").change(function () {
            var messagesBox = $('#m');
            var groupChatSelect = $('#typeGroupChat');
            var friendsChatSelect = $('#typeFriendsChat');
            switch ($(this).children('option:selected').val()) {
                case "worldChat":
                    messagesBox.attr("class", "world");
                    groupChatSelect.hide();
                    friendsChatSelect.hide();
                    showChatView("messages");
                    break;
                case "groupChat":
                    messagesBox.attr("class", "group");
                    groupChatSelect.show();
                    friendsChatSelect.hide();
                    if (Groups.length > 0) {
                        showChatView("messages_groups_" + Groups[0]);
                    }
                    break;
                case "userChat":
                    messagesBox.attr("class", "friends");
                    groupChatSelect.hide();
                    friendsChatSelect.show();
                    if (Friends.length > 0) {
                        showChatView("messages_friends_" + Friends[0]);
                    }
                    break;
                default:
                    break;
            }
        });

        $("#typeGroupChat").change(function () {
            var chatViewId = "messages";
            var groupId = $("#typeGroupChat").children('option:selected').val();
            chatViewId += "_groups_" + groupId;
            showChatView(chatViewId);
        });

        $("#typeFriendsChat").change(function () {
            var chatViewId = "messages";
            var friendId = $("#typeFriendsChat").children('option:selected').val();
            chatViewId += "_friends_" + friendId;
            showChatView(chatViewId);
        });

        $('#m').focus(function () {
            $(this).bind("keyup", function () {
                socket.emit("typing");
            });
        });

        socket.on("p2p messages", function (userid, msg) {
            var chatViewId = "messages";
            chatViewId += "_friends_" + userid;
            $('#' + chatViewId).append($('<li class="userChat">').text("From Userid [" + userid + "]  ==> " + msg));
        });

        socket.on('group messages', function (userid, group, msg) {
            var chatViewId = "messages";
            chatViewId += "_groups_" + group;
            $('#' + chatViewId).append($('<li class="groupChat">').text("From Group [" + group + ":" + userid + "] ==> " + msg));
        });

        socket.on('world messages', function (msg) {
            $('#messages').append($('<li class="worldChat">').text("From World: ==> " + msg));
        });
    }

    function hideLoginView($) {
        $("#loginView").hide();
    }

    function createLoginView($) {
        var loginForm =
                '<div id="loginView">'
                + '<h3> Login </h3>'
                + '<form action="" id="loginForm">'
                + '	<div id="form_left">'
                + '		<div class="form_input"><input type="text" name="" id="username" autocomplete="off" onfocus="this.value=\'\'" placeholder="Username" value="100112301"/></div>'
                + '		<div class="form_input"><input type="password" name="" id="password" autocomplete="off" onfocus="this.value=\'\'" placeholder="Password" value="123456"/></div>'
                + '	</div>'
                + '	<div id="form_right"><button id="loginFormClear">Clear</button><button id="loginFormSubmit">Login</button></div>'
                + '</form>'
                + '</div>';
        $(loginForm).appendTo('body');

        $('#loginFormClear').click(function () {
            $('#username').val("");
            $('#password').val("");
            return false;
        });

        $('#loginFormSubmit').click(function () {
            socket.emit('login', $('#username').val(), $('#password').val(), function (err, user, session, groups, friends) {
                if (err) {
                    alert("login failed!");
                    console.error("login failed!");
                    return;
                }
                console.error("login success!");
                UserId = user;
                SessionId = session;
                Groups = Groups.concat(groups);
                Friends = Friends.concat(friends);

                hideLoginView($);
                createChatView($);
            });
            return false;
        });

    }

    $(function ($) {
        createLoginView($);
    });

    socket.on("typing", function (user) {
        $("title").html(user + " is typing...");
        setTimeout(function () {
            $("title").html("Socket.IO chat");
        }, 1000);
    });
</script>
</html>